package asserts

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"xrt/core"
	"xrt/utils/file/log"
	path2 "xrt/utils/file/path"
)

func AssertFile(filePath string) []byte {
	if core.IsPkg() {
		if rawData, ok := assertsData[filePath]; ok {
			return rawData
		}
	} else {
		if fileData, err := ioutil.ReadFile(filePath); err == nil {
			return fileData
		}
	}
	log.Errorf("Current Request FilePath: [%s] Not Exists.", filePath)
	return nil
}

func AssertFileExists(filePath string) bool {
	exists := false
	if core.IsPkg() {
		_, exists = assertsData[filePath]
	} else {
		exists, _ = path2.Exists(filePath)

	}
	return exists
}

func AssertListDir(dirPath string) []string {
	var matchFile []string
	if core.IsPkg() {
		for key := range assertsData {
			if strings.HasPrefix(key, dirPath) {
				matchFile = append(matchFile, key)
			}
		}
	} else {
		if err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
			if dirPath != path {
				matchFile = append(matchFile, path)
			}
			return nil
		}); err != nil {
			return nil
		}
	}
	return matchFile
}

var assertsData = map[string][]byte{}
